package cn.zch.soft.util.qrcode.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.reflect.Array;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Map;
//import org.json.JSONObject;
public class Helper {
  public static final int AIR_FILTER_ID = 698;
  public static final int PLACE_BUY = 0;
  public static final String YYYY_MM_DD_HH_MM_SS_WORD = "yyyy年MM月dd日 HH时mm分ss秒";
  public static final String YYYY_MM_DD_WORD = "yyyy年MM月dd日";
  public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
  public static final String YYYY_MM_DD = "yyyy-MM-dd";
  public static final String WXOPENIDKEY = "WXOPENIDKEY";
  public static final String WXNEWTHEOWNER = "WXNEWTHEOWNER";
  public static final String ACCESS_TOKEN = "ACCESS_TOKEN";
  public static final String ACCESS_TOKEN_FILE = "access_token.so";
  public static final String SERVER_HOT_LINE = "4006562230";
  public static String getBasepath(HttpServletRequest request) {
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    return basePath;
  }
  /**
   * 判断String类型是否为空
   */
  public static boolean isNull(String value) {
    if (value == null) {
      return true;
    }
    return value.trim().length() == 0;
  }
  public static boolean isNull(Object value) {
    if (value == null) {
      return true;
    }
    if (value.getClass().isArray()) {
      if (Array.getLength(value) == 0) {
        return true;
      }
    }
    if (value instanceof Collection<?>) {
      Collection<?> collection = (Collection<?>) value;
      return collection.isEmpty();
    }
    else if (value instanceof Map<?, ?>) {
      Map<?, ?> map = (Map<?, ?>) value;
      return map.isEmpty();
    }
    else if (value instanceof String) {
      String string = (String) value;
      return isNull(string);
    }
    return false;
  }
  public static String checkNull(Object val) {
    if (val == null) {
      return "";
    }
    return val.toString().trim();
  }
  public static int toInt(Object value) {
    if (value == null) {
      return 0;
    }
    if (value instanceof Number) {
      Number number = (Number) value;
      return number.intValue();
    }
    try {
      return Integer.parseInt(value.toString());
    }
    catch (Exception e) {
      return 0;
    }
  }
  public static String format(int num, int length) {
    StringBuffer buffer = new StringBuffer(Integer.toString(num));
    while (buffer.length() < length) {
      buffer.insert(0, "0");
    }
    return buffer.toString();
  }
  public static String readFile() {
    try {
      File f = new File(ACCESS_TOKEN_FILE);
      if (!f.exists()) {
        try {
          f.createNewFile();
          System.out.println(f.getAbsolutePath());
        }
        catch (IOException e) {
        }
      }
      InputStreamReader br1 = new InputStreamReader(new FileInputStream(f));
      BufferedReader br2 = new BufferedReader(br1);
      String s = "";
      String str = br2.readLine();
      while (str != null) {
        // StringUtil.println(str);
        s = s + str;
        str = br2.readLine();
      }
      br2.close();
      br1.close();
      return s;
    }
    catch (FileNotFoundException e) {
      return "";
    }
    catch (IOException e) {
      return "";
    }
  }
  public static void writeFile(String text) {
    try {
      File f = new File(ACCESS_TOKEN_FILE);
      if (!f.exists()) {
        try {
          f.createNewFile();
        }
        catch (IOException e) {
        }
      }
      OutputStreamWriter bw1 = new OutputStreamWriter(new FileOutputStream(f));
      BufferedWriter bw2 = new BufferedWriter(bw1);
      bw2.write(text);
      bw2.flush();
      bw2.close();
      bw1.close();
    }
    catch (FileNotFoundException e) {
    }
    catch (IOException e) {
    }
  }
  public static java.sql.Timestamp geTimestamp() {
    // return new java.sql.Timestamp(new Date().getTime());
    return new java.sql.Timestamp(System.currentTimeMillis());
  }
  public static void showMessage(HttpServletRequest req, javax.servlet.http.HttpServletResponse resp, String msg, String button) {
    req.setAttribute("message", msg);
    req.setAttribute("button", button);
    String href = Helper.getBasepath(req) + req.getServletPath() + "?" + Helper.checkNull(req.getQueryString());
    req.setAttribute("href", href);
    forword(req, resp, "messages/messages.jsp");
  }
  public static void forword(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String page) {
    try {
      page = page.startsWith("/") ? page : "/" + page;
      request.getRequestDispatcher(page).forward(request, response);
    }
    catch (Exception e) {
    }
  }
  public static void sendRedirect(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String page) {
    try {
      page = page.startsWith("/") ? page : "/" + page;
      String contextPath = request.getContextPath();
      if (!"/".equals(contextPath)) {
        page = contextPath + page;
      }
      response.sendRedirect(page);
    }
    catch (Exception e) {
    }
  }
  public static boolean isPC(HttpServletRequest request) {
    try {
      String user_agent = request.getHeader("user-agent");
      if (user_agent == null) {
        return false;
      }
      if (user_agent.indexOf("Opera") != -1) {
        if (user_agent.indexOf("Android") != -1) {
          return false;
        }
      }
      if (user_agent.indexOf("WPDesktop") != -1) {
        return false;
      }
      if (user_agent.indexOf("Nokia") != -1) {
        return false;
      }
      if (user_agent.indexOf("iPad") != -1) {
        return true;
      }
      if (user_agent.indexOf("iPhone") != -1) {
        return false;
      }
      if (user_agent.indexOf("Mobile") != -1) {
        return false;
      }
      if (user_agent.indexOf("WAP") != -1) {
        return false;
      }
    }
    catch (Exception e) {
    }
    return true;
  }
  /********************************************/
  //产生短网址
  public static String generateShortUrlWithBaidu(String url) {
    try {
      HttpClient client = new HttpClient();
      PostMethod post = new PostMethod("http://dwz.cn/create.php?url=" + url);
      post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
      client.executeMethod(post);
      // 测试输出 {"status":-1,"err_msg":"您输入的域名暂不包括短网址","longurl":""}
      String result = new String(post.getResponseBodyAsString().getBytes(StandardCharsets.UTF_8));
      System.out.println("result " + result);
      // post.releaseConnection();
      post.recycle();
      //      JSONObject jsnObject = new JSONObject(result);
      //      String shortUrl = jsnObject.getString("longurl");
      JSONObject jsonObject = JSON.parseObject(result);
      return jsonObject.getString("longurl");
    }
    catch (Exception e) {
      //e.printStackTrace();
      return null;
    }
  }
  public static String generateShortUrlWithDWZIS(String url) {
    try {
      HttpClient client = new HttpClient();
      PostMethod post = new PostMethod("http://goo.gd/action/json-is.php?url_long=" + url);
      post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
      client.executeMethod(post);
      //{"object_type":"","result":true,"url_short":"http://t.cn/RKyIc1g","object_id":"","url_long":"http://1.singbon.com","type":0}]}
      String result = new String(post.getResponseBodyAsString().getBytes(StandardCharsets.UTF_8));
      System.out.println("result1 " + result);
      // post.releaseConnection();
      post.recycle();
      //result = result.replace("[","").replace("]","")
      System.out.println("result2 " + result);
      JSONObject jsnObject = JSON.parseObject(result);
      System.out.println("jsnObjectWithSina " + jsnObject);
      String shortUrl = jsnObject.getString("shorturl");
      return shortUrl;
    }
    catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  /********************************************/
  public static Image getImg(String path) {
    ImageIcon imageIcon = new ImageIcon(path); // Icon由图片文件形成
    Image image = imageIcon.getImage(); // 但这个图片太大不适合做Icon
    // 为把它缩小点，先要取出这个Icon的image ,然后缩放到合适的大小
    Image smallImage = image.getScaledInstance(30, 20, Image.SCALE_FAST);
    // 再由修改后的Image来生成合适的Icon
    // ImageIcon smallIcon = new ImageIcon(smallImage);
    // 最后设置它为按钮的图片
    // JButton iconButton = new JButton(smallIcon);
    // 而由ImageIcon类到Image类，可以通过：
    // ImageIcon imageIcon2 = new ImageIcon("duke.gif"); // Icon由图片文件形成
    // JFrame jf=null;
    // jf.setImageIcon(ImageIcon.getImage());
    return smallImage;
  }
}
